package com.ukao.steward.ui.valetRunners.toShop;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.base.MvpFragment;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.pesenter.valetRunners.ToShopPresenter;
import com.ukao.steward.util.ActivityUtils;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.KeyBoardUtil;
import com.ukao.steward.util.T;
import com.ukao.steward.view.valetRunners.ToShopView;
import com.ukao.steward.widget.ClearEditText;
import com.ukao.steward.widget.StateImageView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.hoang8f.android.segmented.SegmentedGroup;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ToShopFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ToShopFragment#newInstance} factory method to
 * create an instance of this fragment.
 * by 谢敏
 */
public class ToShopFragment extends MvpFragment<ToShopPresenter> implements ToShopView{
    public  static final int  BATCH_TO_SHOP_FLAG=100;  //批次到店
    public  static final int  ORDER_TO_SHOP_FLAG=101;  //订单到店
    private int toShopQueryMode =0;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
     //第三方的封装好的RadioGroup
    @BindView(R.id.menu_segmented_group)
    SegmentedGroup segmentedGroup;
    //确认按钮
    @BindView(R.id.confirm_btn)
     Button  confirmBtn;
    //扫描按钮
    @BindView(R.id.scanning_btn)
    StateImageView scanningBtn;
    //标题按钮
    @BindView(R.id.title)
   TextView tvTitle;
    //返回按钮
    @BindView(R.id.back_btn)
     ImageView  ivBackBtn;
   private Unbinder  unbinder;
   @BindView(R.id.et_code_input)
    ClearEditText  etCodeInput;



    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public ToShopFragment() {

    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ToShopFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ToShopFragment newInstance(String param1, String param2) {
        ToShopFragment fragment = new ToShopFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected ToShopPresenter createPresenter() {
        return new ToShopPresenter(this);
    }

    /**
     *  初始化View
     */
    @Override
    protected void initView() {
        //批号79460954  订单号
        etCodeInput.setText("");
        tvTitle.setText("到店");
        toShopQueryMode=BATCH_TO_SHOP_FLAG;  //设置默认的搜撒方式
        segmentedGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                   switch (checkedId){
                       case R.id.batch_btn:   //批次到店
                           toShopQueryMode = BATCH_TO_SHOP_FLAG;
                           etCodeInput.setHint("请输入出厂批号");
                         break;
                       case R.id.order_btn:   //订单到店
                           toShopQueryMode =ORDER_TO_SHOP_FLAG;
                           etCodeInput.setHint("请输入出厂单号");
                            break;
                   }
            }
        });

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       View view =inflater.inflate(R.layout.fragment_to_shop, container, false);
        unbinder =ButterKnife.bind(this,view);
        return view;
    }
    @OnClick({R.id.back_btn,R.id.confirm_btn,R.id.scanning_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.confirm_btn:
                if(!CheckUtils.isEmpty(getText(etCodeInput))){
                    super.mvpPresenter.queryToShopCode(etCodeInput.getText().toString(),toShopQueryMode);
                }else {
                    T.show("请输入正确的订单号/运单号");
                }
                break;
            case R.id.scanning_btn:   //扫码
                Intent mIntent = ActivityUtils.JumpToBundleActivity(_mActivity);
                startActivityForResult(mIntent, Constant.REQUEST_CODE);
                break;
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();
    }
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }


    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //解除黄油刀的绑定
        unbinder.unbind();
    }
    @Override
    public void onSearchSucceed(int id, String number, int QueryMode) {
        //跳转碎片
        super.start(ToShopCheckFragment.newInstance(id, number, QueryMode));
    }
    //onActivityResult
    @Override
    protected void initListener(){
        //监听回车键
          etCodeInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
              @Override
              public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                  if (!CheckUtils.isNull(event) && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                          || actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NEXT) {
                      String strEditText = getText(etCodeInput);
                      if (!CheckUtils.isEmpty(strEditText)) {
                         mvpPresenter.queryToShopCode(etCodeInput.getText().toString(),toShopQueryMode);
                          KeyBoardUtil.hideInputmethod(etCodeInput);
                          etCodeInput.setText("");
                          etCodeInput.requestFocus();
                      }
                  }
                  return false;
              }
          });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == _mActivity.RESULT_OK) {
            switch (requestCode) {
                case Constant.REQUEST_CODE:
                    String  code=data.getStringExtra(Constant.ARG_PARAM1);
                    etCodeInput.setText(code);
                    if(!CheckUtils.isEmpty(getText(etCodeInput))){
                        super.mvpPresenter.queryToShopCode(etCodeInput.getText().toString(),toShopQueryMode);
                    }else {
                        T.show("请输入正确的订单号/运单号");
                    }
                    break;

            }
        }

    }

    /**
     * 接受成功
     */
    @Override
    public void onReceivingSucceed() {

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
